/**
 * Created by sunzhijun on 2019/01/01.
 */
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
// import ReferSearch from "../../../public/components/referSearch/index";
// import EmptyImg from '../../../../hrpub/common/components/emptyImg';
import {high, createPage, base, getUrlParam, toast, promptBox} from 'nc-lightapp-front';
import {hrAjax as ajax} from 'src/hrpub/common/utils/utils';
import SetModal from './components/SetModal';
// import zhCN from "rc-calendar/lib/locale/zh_CN";
// import do_print from '../../../../hrpub/common/utils/print';
import { handleHash } from 'src/hrpub/common/utils/utils';
import printPage from './functions/print';
import './index.less';

let tableid='seqcontrollist';
let modifyDataArr = [];
const appcode = "60070520", pagecode = "60070520p", format = "YYYY-MM-DD";
const {NCTable, NCDatePicker, NCModal, NCButton, NCSwitch} = base;

const moduleId = "hihr6007"
const domainName = "hrhi"

class MainPage extends Component {
    constructor(props) {
        super(props);
        if (props.use) {
            props.use.editTable(tableid);
        }
        this.config = {
            pagecode: pagecode,
            appcode: appcode
        };
        this.state = {
        	showMode: 'browse',
        	setModalVisible: false
        }
        props.createUIDom(this.config, (data) => {
            this.setState({
                buttons: data.button || [],
                context: data.context || {},
                pk_org: 'GLOBLE00000000000000',
                telName: data.template.name || ''
            });
            props.meta.setMeta(data && data.template ? data.template : {},()=>{
            	this.fetchTableData()
            });
            props.button.setButtons(data && data.button ? data.button : {});
        });
    }

    componentWillMount() {
        window.location.hash = '?page=201908241349';
        let callback = (json, status, inlt) => {
            if (status) {
                this.lang = json
                this.setState({json, inlt})//存json和inlt到页面state中并刷新页面
            }
        }
        this.props.MultiInit.getMultiLang({moduleId: moduleId, domainName: domainName, callback})
    }

    componentDidMount() {
        this.updateButtonStatus();
        // 计算列表的高度
        // let bodyH = this.refs.getContainerDom.offsetHeight;
        // let headerH = this.refs.getHeaderDom.offsetHeight;
        // this.setState({
        //     tableHeight: bodyH - headerH - 44
        // })
    }

    //数据初始化
    fetchTableData(){
    	ajax ({
            url: '/nccloud/hrhi/seqcontrol/InitSeqcontrolAction.do',
            data: {
                'pk_org': this.state.pk_org,
            },
            success: res => {
                if(res.success){
                	this.props.editTable.setTableData(tableid,{rows: res.data&&res.data.grid.seqcontrollist.rows||[]});
                	if(!res.data.isenable){
                		this.props.button.setButtonDisabled('edit',true);
                	}else{
                		this.props.button.setButtonDisabled('edit',false);
                	}
                    this.updateShowMode('browse');
                }
            }
        })
    }

    //保存1
    saveTableData () {
        // let data = this.props.editTable.getAllRows(tableid, true);
        // let temp = Object.assign([],data)
        let modelInfo = {
            model: ({
                rows: modifyDataArr
            }),
            pk_org: this.state.pk_org
        }
        ajax({
            url: '/nccloud/hrhi/seqcontrol/SaveSeqcontrol1Action.do',
            type: 'post',
            data: modelInfo,
            success: res => {
            	if(res.success){
            		this.saveTableData2(modelInfo)
            	}else{
            		promptBox({
                        color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                        title: this.state.json['hihr-000003'],                // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输/* 国际化处理： 确认删除*/
                        content: res.data.confirmMsg,             // 提示内容,非必输/* 国际化处理： 您确定要删除所选数据么?*/
                        noFooter: false,                // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                        noCancelBtn: false,             // 是否显示取消按钮,，默认显示(false),非必输
                        beSureBtnName: this.state.json['hihr-000006'],          // 确定按钮名称, 默认为"确定",非必输/* 国际化处理： 确定*/
                        cancelBtnName: this.state.json['hihr-000007'],         // 取消按钮名称, 默认为"取消",非必输/* 国际化处理： 取消*/
                        hasCloseBtn:true,             //显示“X”按钮，默认不显示，不显示是false，显示是true
                        beSureBtnClick: ()=>{ this.saveTableData2(modelInfo) },   // 确定按钮点击调用函数,非必输
                        // cancelBtnClick: functionCancel,  // 取消按钮点击调用函数,非必输
                        // closeBtnClick:functionClose, //关闭按钮点击调用函数，非必输
                        closeByClickBackDrop:false,//点击遮罩关闭提示框，默认是true点击关闭，阻止关闭是false
                    })
            	}
            },
            error: rej => {
                toast({color:"warning",content: rej.message})
                if (this.state.showMode === 'browse') {
                    this.fetchTableData()
                }
                // this.props.editTable.cancelEdit(tableid);
            }
        })
    }
    //保存2
    saveTableData2(data){
    	ajax({
            url: '/nccloud/hrhi/seqcontrol/SaveSeqcontrol2Action.do',
            type: 'post',
            data: data,
            success: res => {
                this.fetchTableData();
                modifyDataArr=[];
            },
            error: rej => {
                toast({color:"warning",content: rej.message})
                if (this.state.showMode === 'browse') {
                    this.fetchTableData()
                }
                // this.props.editTable.cancelEdit(tableid);
            }
        })
    }
    //确认弹窗
    promptBoxModal(context,func,args){
        promptBox({
            color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
            title: this.state.json['hihr-000003'],                // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输/* 国际化处理： 确认删除*/
            content: context,             // 提示内容,非必输/* 国际化处理： 您确定要删除所选数据么?*/
            noFooter: false,                // 是否显示底部按钮(确定、取消),默认显示(false),非必输
            noCancelBtn: false,             // 是否显示取消按钮,，默认显示(false),非必输
            beSureBtnName: this.state.json['hihr-000006'],          // 确定按钮名称, 默认为"确定",非必输/* 国际化处理： 确定*/
            cancelBtnName: this.state.json['hihr-000007'],         // 取消按钮名称, 默认为"取消",非必输/* 国际化处理： 取消*/
            hasCloseBtn:true,             //显示“X”按钮，默认不显示，不显示是false，显示是true
            // beSureBtnClick: ()=>{ this.resetTableData() },   // 确定按钮点击调用函数,非必输
            beSureBtnClick:  ()=> { func(args) } ,   // 确定按钮点击调用函数,非必输
            // cancelBtnClick: functionCancel,  // 取消按钮点击调用函数,非必输
            // closeBtnClick:functionClose, //关闭按钮点击调用函数，非必输
            closeByClickBackDrop:false,//点击遮罩关闭提示框，默认是true点击关闭，阻止关闭是false
        })
    }
    //重置数据
    resetTableData(){
    	ajax({
            url: '/nccloud/hrhi/seqcontrol/ResetSeqcontrolAction.do',
            type: 'post',
            data: {
                'pk_org': this.state.pk_org,
            },
            success: res => {
                if (res.success) {
                    this.updateShowMode('browse');
                    this.fetchTableData()
                    toast({color:"success"})
                } 
            },
            error: rej => {
                toast({color:"warning",content: rej.message})
            }
        })
    }
    //刷新
    refreshTableData(){
    	ajax({
            url: '/nccloud/hrhi/seqcontrol/RefreshSeqcontrolAction.do',
            type: 'post',
            data: {
                'pk_org': this.state.pk_org,
            },
            success: res => {
                if (res.success) {
                    this.updateShowMode('browse');
                    this.fetchTableData()
                    toast({color:"success"})
                } 
            },
            error: rej => {
                toast({color:"warning",content: rej.message})
            }
        })
    }

    //获取某一处修改的数据索引
    searchIndex(arr,id){
    	for(let i=0; i < arr.length; i++){
    		if(arr[i].rowid == id){
    			return i;
    		}
    	}
    }

    //编辑数据后重组
    checkedOrNot (a,b,c,d,e,f,g,h) {
    	let index = this.searchIndex(modifyDataArr,g.rowid);
    	if(index >= 0){
    		modifyDataArr.splice(index,g);
    	}else{
    		modifyDataArr.push(g);
    	}
    }

    // 按钮是否显示，按钮是否可用
    updateButtonStatus () {
        var showMode = this.state.showMode
        this.props.button.setButtonsVisible({
        	set: showMode === 'browse',
            edit: showMode === 'browse',
            refresh: showMode === 'browse',
            reset: showMode === 'browse',
            save: showMode === 'edit',
            cancel: showMode === 'edit',
            print: showMode === 'browse'
        })
    }

    // 更新界面状态
    updateShowMode(showMode) {
    	var oldMode = this.state.showMode;
        this.setState({
            showMode: showMode
        }, () => {
            this.updateButtonStatus()
        })
        if(oldMode === showMode) {
            return;
        }
        if('edit' === showMode) {
            this.props.editTable.setStatus(tableid,'edit');
            // this.props.editTable.setColEditableByKey(tableid, "table",false)
        } else {
            this.props.editTable.cancelEdit(tableid);
        }
    }

    // 打印
    print(tableid) {
        printPage.call(this,tableid);
    }

     // 统一处理按钮事件
    onBtnOperation(props, btncode, areacode, opt, recordRow, index) {
        let pk_id = '';
        let record = null;
        if(recordRow) {
            record = JSON.parse(JSON.stringify(recordRow));
            pk_id = record.values.pk_dataio_intface.value;
            this.setState({'row_id': pk_id})
        }
        switch(btncode) {
        	case 'set': 
        		this.setState({
        			setModalVisible: true
        		})
        	break;
            case 'edit':
            	 this.updateShowMode('edit');
                // this.props.form.setFormStatus(tableid, 'edit');
                // this.props.form.EmptyAllFormValue(tableid);
                // this.assignStepModal.show('assign', 'add', '');
            break;
            case 'reset':
                let lan1 = this.state.json['hihr-000001'];
                this.promptBoxModal(lan1,this.resetTableData.bind(this));
            break;
            case 'refresh': 
            	this.refreshTableData();
            break;
            case 'save':
                this.saveTableData();
            break;
            case 'cancel':
                let lan2 = this.state.json['hihr-000002'];
                this.promptBoxModal(lan2,this.updateShowMode.bind(this),'browse');
            break;
            case 'print': 
                this.print(tableid);
                // do_print(document.querySelector('#tableListData'), {
                //     title: this.state.telName,
                //     maker: this.state.json['hihr-000004'],
                //     date: this.state.json['hihr-000005']
                // })
            break;
            case 'output':
                this.print(tableid);
                break;
            default:
            break;

        }

    }

    render() {
    	let {button,  modal, table, form, cardTable, editTable } = this.props;
        let {createButtonApp} = button;
        let {createEditTable} = editTable;
       	const {setModalVisible, pk_org } = this.state;
        return (
            <div className="nc-single-table" ref="getContainerDom">
                <div className="nc-singleTable-header-area" ref="getHeaderDom">
                    {/* 按钮区  btn-group */}
                    <div className="header-button-area">
                        {createButtonApp({
                                area: 'head',//按钮注册中的按钮区域
                                buttonLimit: 1,
                                onButtonClick: (props, btncode) => this.onBtnOperation(props, btncode, 'list', this),
                                popContainer: document.querySelector('.header-button-area')
                        })}
                    </div>
                </div>
                <div className='nc-singleTable-table-area"' id="tableListData">
                    {/* 生成表格 */}
                    {createEditTable(tableid,{   
                        showIndex: true, 		//显示序列号
                        onAfterEvent: this.checkedOrNot.bind(this),				//表格状态监听
                        // height: tableHeight,
                        adaptionHeight: true
                    })}
                </div>
                {
                    setModalVisible ? <SetModal 
                        {...this.props}
                        setModalVisible={setModalVisible}
                        pk_org={pk_org}
                        onClose={() => {
                            this.setState({
                                setModalVisible: false
                            });
                            this.fetchTableData();
                        }}
                    /> : ''
                }
            </div>
        );
    }
}

const HomePage = handleHash('201908241349', 'c=60070520&p=60070520p')(createPage({})(MainPage));
ReactDOM.render(<HomePage/>, document.querySelector('#app'));

export default MainPage;
